//
//  CZPhotoBrowserViewController.swift
//  czbkiosweibo5
//
//  Created by zhangping on 15/10/23.
//  Copyright © 2015年 zhangping. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 照片浏览控制器
class CZPhotoBrowserViewController: UIViewController {
    
    // MARK: - 属性
    /// collectionViewCell 重用标示
    private let CZPhotoBrowserViewCellIdentifier = "CZPhotoBrowserViewCellIdentifier"
    
    /// 要显示的大图的url数组
    var urls: [NSURL]
    
    /// 点击的cell的indexPath
    var indexPath: NSIndexPath
    
    // MARK: - 构造函数
    init(urls: [NSURL], indexPath: NSIndexPath) {
        self.urls = urls
        self.indexPath = indexPath
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 将控制器的view的宽度加大 15 
        view.frame.size.width += 15

        prepareUI()
        
        // 设置页码标签内容
        pageLabel.text = "\(indexPath.item + 1) / \(urls.count)"
        
        view.backgroundColor = UIColor.blackColor()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    // MARK: - 按钮点击时间
    /// 关闭按钮点击事件
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 保存按钮点击事件
    func save() {
        // 获取当前正在显示的图片
        let indexPath = collectionView.indexPathsForVisibleItems().first!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! CZPhotoBrowserCell
        let image = cell.imageView.image
        
        // 保存图片
        /*
            参数:
                image: 要保存的图片
                completionTarget: 完成后的回调对象
                completionSelector: 完成后的回调方法
        */
        UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    /// 图片保存后的回调方法
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            print("error: \(error)")
            SVProgressHUD.showErrorWithStatus("保存图片失败", maskType: SVProgressHUDMaskType.Black)
            
            return
        }
        
        SVProgressHUD.showSuccessWithStatus("保存图片成功", maskType: SVProgressHUDMaskType.Black)
    }
    
    // MARK: - 准备UI
    /// 准备UI
    private func prepareUI() {
        // 添加子控件
        view.addSubview(collectionView)
        view.addSubview(pageLabel)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["cv": collectionView, "pl": pageLabel, "cb": closeButton, "sb": saveButton]
        // collectionView
        // 填充父控件
        collectionView.frame = view.bounds
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        // pageLabel
        // 水平居中
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        // 垂直 在父控件顶部,距离20
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 20))
        
        // 关闭 保存 按钮
        // v
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        // h
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cb(75)]-(>=0)-[sb(75)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        // 按钮添加点击事件
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 准备CollectionView
        prepareCollectionView()
    }
    
    // MARK: - 准备CollectionView
    /// 准备CollectionView
    private func prepareCollectionView() {
        // 注册cell
        collectionView.registerClass(CZPhotoBrowserCell.self, forCellWithReuseIdentifier: CZPhotoBrowserViewCellIdentifier)
        
        // 设置数据源
        collectionView.dataSource = self
        
        // 设置代理
        collectionView.delegate = self
        
        // 获取collectionView的layout
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        // 设置layout
        layout.itemSize = view.bounds.size
        
        // 滚动方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        // 分页显示
        collectionView.pagingEnabled = true
        collectionView.backgroundColor = UIColor.clearColor()
    }
    
    // MARK: - 懒加载
    /// collectionView
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    
    /// 关闭按钮
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, textColor: UIColor.whiteColor(), bkgImageName: "health_button_orange_line")
    /// 保存按钮
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, textColor: UIColor.whiteColor(), bkgImageName: "health_button_orange_line")
    
    /// 页码标签
    private lazy var pageLabel: UILabel = UILabel(textColor: UIColor.whiteColor(), fontSize: 12)
}

// MARK: - 扩展 CZPhotoBrowserViewController 实现 UICollectionViewDataSource 数据源 和 UICollectionViewDelegate 代理
extension CZPhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    /// 返回 cell 的数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    /// 返回 cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZPhotoBrowserViewCellIdentifier, forIndexPath: indexPath) as! CZPhotoBrowserCell
        
        // 设置cell背景为随机色
        cell.backgroundColor = UIColor.clearColor()
        
        // 设置cell要显示的url
        cell.url = urls[indexPath.item]
        
        return cell
    }
    
    // 监听collectionView停止滚动
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 获取正在显示的cell
        if let indexPath = collectionView.indexPathsForVisibleItems().first {
            // 设置给当前 indexPath 属性
            self.indexPath = indexPath
            
            // 设置页码
            pageLabel.text = "\(indexPath.item + 1) / \(urls.count)"
        }
    }
}
